#include "directioncontrolwidget.h"
#include <QPainter>
#include <QMouseEvent>
#include <QtMath>
#include <QApplication>
#include <QPainterPath>

DirectionControlWidget::DirectionControlWidget(QWidget *parent)
    : QWidget(parent)
{
    setAttribute(Qt::WA_StyledBackground, true);
    setStyleSheet("background-color: transparent;");
}

void DirectionControlWidget::paintEvent(QPaintEvent* /*event*/)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // 计算中心点和半径
    m_center = rect().center();
    m_radius = qMin(width(), height()) / 2-5;
    // 绘制各个部分
    drawBackground(painter, m_radius /4);
    drawCenterPoint(painter,m_radius /4);
}

void DirectionControlWidget::drawBackground(QPainter& painter, int innerRadius)
{
    // 绘制底层背景
    painter.setPen(Qt::NoPen);
    painter.setBrush(QColor(18,18,18,128));
    painter.drawEllipse(m_center, m_radius, m_radius);

    // 如果正在拖动，添加边缘高亮效果
    if (m_isDragging) {
        QPoint delta = m_currentPos - m_center;
        double length = qSqrt(delta.x() * delta.x() + delta.y() * delta.y());

        // 计算最大移动半径和当前比例
        int maxMoveRadius = m_radius - innerRadius;
        double ratio = qMin(1.0, length / maxMoveRadius);

        // 计算圆心偏移量 (向拖动反方向偏移半径的5%)
        QPoint offset = QPoint(
            -delta.x()*m_radius/length *1.5,
            -delta.y()*m_radius/length *1.5
        );

        QRadialGradient baseGradient(m_center+offset, m_radius*2.5);
        baseGradient.setColorAt(0, QColor(0, 0, 0, 0));
        baseGradient.setColorAt(0.8, QColor(0, 0, 0, 0));
        baseGradient.setColorAt(1, QColor(0, 255, 255, 255*ratio));

        // 绘制基础渐变
        painter.setPen(Qt::NoPen);
        painter.setBrush(baseGradient);
        QPainterPath path1;
        path1.addEllipse(m_center, m_radius, m_radius);

        QPainterPath path2;
        path2.addEllipse(m_center + offset, m_radius*2, m_radius*2);

        // 计算两个圆的相交区域
        QPainterPath intersectPath = path1.subtracted(path2);
        painter.drawPath(intersectPath);
    }
}

void DirectionControlWidget::drawCenterPoint(QPainter& painter, int innerRadius)
{
    if (m_isDragging) {
        QPixmap pixmap(":/images/ctrl_center_drag.png");
        QTransform transform;
        // 计算拖动角度
        QPoint delta = m_currentPos - m_center;
        double rotate = qAtan2(delta.y(), delta.x());
        innerRadius = innerRadius*(abs(sin(rotate+M_PI/2))+abs(cos(rotate+M_PI/2)));
        transform.rotate(rotate * 180 / M_PI+90);
        QPixmap rotatedPixmap = pixmap.transformed(transform);
        painter.drawPixmap(m_currentPos.x() - innerRadius, m_currentPos.y() - innerRadius,
                         2 * innerRadius, 2 * innerRadius, rotatedPixmap);
    } else {
        painter.drawPixmap(m_center.x() - innerRadius, m_center.y() - innerRadius,
                         2 * innerRadius, 2 * innerRadius, QPixmap(":/images/ctrl_center.png"));
    }
}

void DirectionControlWidget::startDragging(const QPoint& pos)
{
    Q_UNUSED(pos);
    // 抓取鼠标
    grabMouse();
}

void DirectionControlWidget::mouseMoveEvent(QMouseEvent *event)
{
    m_isDragging = true;
    // 限制移动位置，确保控制点不会超出边界
    m_currentPos = limitToCircle(event->pos());
    calculateDirection(m_currentPos);
    update();
}

void DirectionControlWidget::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton && m_isDragging) {
        m_isDragging = false;
        m_currentPos = m_center;
        m_xSpeed = 0.0;  // 重置速度
        m_ySpeed = 0.0;
        emit directionChanged(0, 0);
        releaseMouse();  // 释放鼠标
        update();

        // 将释放事件传递给父窗口
        QPoint parentPos = mapTo(parentWidget(), event->pos());
        QMouseEvent *newEvent = new QMouseEvent(
            QEvent::MouseButtonRelease,
            parentPos,
            event->button(),
            event->buttons(),
            event->modifiers()
            );
        QApplication::postEvent(parentWidget(), newEvent);
    }
}

void DirectionControlWidget::calculateDirection(const QPoint& pos)
{
    QPoint delta = pos - m_center;
    double length = qSqrt(delta.x() * delta.x() + delta.y() * delta.y());

    // 计算最大移动半径
    int ringWidth = qMin(width(), height()) / 3;
    int innerRadius = m_radius - ringWidth;
    int maxMoveRadius = m_radius - innerRadius;

    // 计算从中心点到当前位置的比例
    double ratio = qMin(1.0, length / maxMoveRadius);

    // 计算单位向量并乘以比例
    double angle = qAtan2(-delta.y(), delta.x());
    m_xSpeed = ratio * qCos(angle);
    m_ySpeed = ratio * qSin(-angle);  // 反转Y轴

    emit directionChanged(m_xSpeed, m_ySpeed);
}

QPoint DirectionControlWidget::limitToCircle(const QPoint& pos)
{
    QPoint delta = pos - m_center;
    double length = qSqrt(delta.x() * delta.x() + delta.y() * delta.y());

    // 最大移动半径需要考虑控制点的大小
    int maxMoveRadius = m_radius*3/4;  // 这是控制点中心的最大移动半径

    // 如果超出最大移动半径，限制到最大移动半径
    if (length > maxMoveRadius) {
        double scale = maxMoveRadius / length;
        return m_center + QPoint(delta.x() * scale, delta.y() * scale);
    }

    return pos;
}

bool DirectionControlWidget::event(QEvent *event)
{
    // 对于鼠标按下和释放事件，先传递给父窗口
    if (event->type() == QEvent::MouseButtonPress ||
        event->type() == QEvent::MouseButtonRelease)
    {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);

        // 将局部坐标转换为父窗口坐标
        QPoint parentPos = mapTo(parentWidget(), mouseEvent->pos());

        // 创建新的鼠标事件
        QMouseEvent *newEvent = new QMouseEvent(
            mouseEvent->type(),  // 使用原始事件类型
            parentPos,
            mouseEvent->button(),
            mouseEvent->buttons(),
            mouseEvent->modifiers()
            );

        // 发送到父窗口
        QApplication::postEvent(parentWidget(), newEvent);

        // 继续处理本控件的事件
        return QWidget::event(event);
    }

    return QWidget::event(event);
}
